package com.micosco.taskremind.ui.handler;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.micosco.taskremind.ui.TaskListRecyclerViewAdapter;

public class TaskListRefreshHandler extends RefreshHandler {
    private static String LOG_TAG = "TaskListUpdateHandler";

    private boolean autoRefresh;
    RecyclerView recyclerView;

    public TaskListRefreshHandler(RecyclerView recyclerView) {
        this.recyclerView = recyclerView;
        this.autoRefresh = false;
    }

    @Override
    public void handleMessage(@NonNull Message msg) {
        if (recyclerView != null) {
            TaskListRecyclerViewAdapter adapter =
                    (TaskListRecyclerViewAdapter) recyclerView.getAdapter();
            if (adapter != null) {
                adapter.notifyItemRangeChanged(0, adapter.getItemCount());
//                for (int i = 0; i < adapter.getItemCount(); i++) {
//                    TaskViewHolder holder =
//                            (TaskViewHolder) recyclerView.findViewHolderForAdapterPosition(i);
//
//                    if (holder == null || !holder.mItem.isOverdue()) {
//                        adapter.notifyItemChanged(i);
//                    }
//                }
            }
        } else {
            Log.e(LOG_TAG, "Instance is not initialized. Auto refresh has been stopped");
            autoRefresh = false;
        }

        if (autoRefresh && msg.what == START_AUTO_REFRESH) {
            sendEmptyMessageDelayed(0, 500);
        }
    }

    @Override
    public void startRefresh() {
        autoRefresh = true;
        sendEmptyMessage(0);
        Log.i(LOG_TAG, "Task list refresh starting.");
    }

    @Override
    public void stopRefresh() {
        autoRefresh = false;
        Log.i(LOG_TAG, "Task list refresh stopping.");
    }

    public void setRecyclerView(RecyclerView recyclerView) {
        this.recyclerView = recyclerView;
    }
}
